import 'package:dio/dio.dart';
import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/httpp.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  // 接收动态路由组件传过来的值
  const ProfilePage({super.key, required this.userInfo});

  final Map userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  // 昵称输入框控制器
  final _nicknameController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 更新昵称输入框的值
    setState(() {
      _nicknameController.text = widget.userInfo['nickName'];
    });
  }

  _showSheet() {
    // 底部半模态弹窗
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      builder: (context) {
        return SizedBox(
          height: 150,
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                onTap: () {
                  _updateProfile(ImageSource.camera);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo),
                title: const Text('相册'),
                onTap: () {
                  _updateProfile(ImageSource.gallery);
                },
              )
            ],
          ),
        );
      },
    );
  }

  _updateProfile(ImageSource type) async {
    try {
      final picker = ImagePicker();
      final XFile? pickedFile = await picker.pickImage(source: type);
      // print(pickedFile?.path);
      if (pickedFile != null) {
        final fd = FormData.fromMap({
          'file': await MultipartFile.fromFile(pickedFile.path),
          'type': 'avatar',
        });
        final res = await http.post('/upload', data: fd);
        // 业务状态吗错误，提示后端信息
        if (res['code'] != 10000) {
          return ToastUtil.showError(res['message']);
        }
        setState(() {
          widget.userInfo['avatar'] = res['data']['url'];
        });
        // 轻提示
        ToastUtil.showSuccess('更新成功');
        // 通过 eventBus 刷新其他页面的用户信息
        // eventBus.fire(RefreshMine());
      }
    } catch (error) {
      ToastUtil.showError('出现错误');
    } finally {
      // 不管成功失败都要关闭弹窗
      // Flutter 的半模态弹窗底层是通过路由实现的，弹窗也是一个路由被压入路由栈。
      Navigator.pop(context);
    }
  }

  // 表单提交
  _onSubmit(String value) async {
    if (value.isEmpty) {
      return ToastUtil.showError('昵称不能为空');
    }
    // 发送网络请求
    await http.put('/userInfo', data: {
      'nickName': value,
    });
    // 通过 eventBus 刷新个人中心的用户信息
    // eventBus.fire(RefreshMine());
    // 轻提示
    ToastUtil.showInfo('昵称更新成功');
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false, // 禁止系统级别的返回
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('个人信息'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
          // 定制标题左侧内容
          leading: IconButton(
            onPressed: () {
              // 返回
              Navigator.pop(context);
              // 刷新个人中心页
              eventBus.fire(RefreshMine());
            },
            icon: const Icon(Icons.arrow_back),
          ),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: [
                  const Text(
                    '头像',
                    style: TextStyle(fontSize: 16),
                  ),
                  const Spacer(),
                  GestureDetector(
                    onTap: () {
                      _showSheet();
                    },
                    child: Row(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: widget.userInfo['avatar'] == null
                              ? Image.asset(
                                  'images/avatar_1.jpg',
                                  width: 30,
                                  height: 30,
                                )
                              : Image.network(
                                  widget.userInfo['avatar'],
                                  width: 30,
                                  height: 30,
                                ),
                        ),
                        const Icon(Icons.arrow_forward_ios, size: 12)
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                const Text('昵称'),
                const Spacer(),
                Expanded(
                  child: TextField(
                    controller: _nicknameController,
                    decoration: const InputDecoration(
                      hintText: '请输入昵称',
                      border: InputBorder.none,
                    ),
                    textAlign: TextAlign.right,
                    onSubmitted: (value) {
                      _onSubmit(value);
                    },
                  ),
                ),
                const Icon(Icons.arrow_forward_ios, size: 12)
              ],
            )
          ],
        ),
      ),
    );
  }
}
